package com.cincc.cincc_pbx.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cincc.cincc_pbx.R;
import com.cincc.cincc_pbx.adapter.InternalAdapter;
import com.cincc.cincc_pbx.adapter.NavAdapter;
import com.cincc.cincc_pbx.common.CallUtil;
import com.cincc.cincc_pbx.common.OkHttpUtils;
import com.cincc.cincc_pbx.constant.CallConstant;
import com.cincc.cincc_pbx.model.InternalContactModel;
import com.cincc.cincc_pbx.model.NavModel;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class InternalActivity extends BaseActivity {
    private static final String TAG = "InternalActivity";

    @Override
    protected int contentLayout() {
        return R.layout.activity_internal_contact;
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        initView();
        requestData(CallConstant.loginModel.getVccId(), "0");
    }

    RecyclerView recyclerView;
    RecyclerView navRecyclerView;
    InternalAdapter internalAdapter;
    NavAdapter navAdapter;

    List<NavModel> navList = new ArrayList<>();

    private void initView() {
        recyclerView = findViewById(R.id.recycler);
        navRecyclerView = findViewById(R.id.nav_recycler);
        recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
        navRecyclerView.setLayoutManager(layoutManager);

        navList.add(new NavModel("0", "联系人"));

        internalAdapter = new InternalAdapter(this, list);
        navAdapter = new NavAdapter(this, navList);
        recyclerView.setAdapter(internalAdapter);
        navRecyclerView.setAdapter(navAdapter);
        internalAdapter.setOnClickItem(item -> {
            if (item.isOrg()) {
                requestData(CallConstant.loginModel.getVccId(), item.getOrgId());
                navList.add(new NavModel(item.getOrgId(), item.getName()));
                navAdapter.notifyDataSetChanged();
            } else {
                showDialog(item);
            }
        });
        navAdapter.setOnClickItem((position, item) -> {
            if (position < navList.size() - 1) {
                List<NavModel> elementsToRemove = navList.subList(position + 1, navList.size());
                navList.removeAll(elementsToRemove);
                navAdapter.notifyDataSetChanged();
                requestData(CallConstant.loginModel.getVccId(), item.getOrgId());
            }
        });
    }

    private void showDialog(InternalContactModel model) {
        List<String> phoneList = new ArrayList<>();
        if (model.getMobile().length() > 0) phoneList.add("手机 : " + model.getMobile());
        phoneList.add("分机 : " + model.getTelephoneNumber());

        String[] array = new String[phoneList.size()];
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asCenterList("请选择外呼项", phoneList.toArray(array),
                        null, 0,
                        (position, text) -> {
                            String phoneNum = array.length == 1 ? model.getTelephoneNumber() : (position == 0 ? model.getMobile() : model.getTelephoneNumber());
                            applyPermission(phoneNum);
                        })
                .show();
    }

    private void applyPermission(String phone) {
        XXPermissions.with(this).permission(CallConstant.AUDIO_PERMISSION_LIST)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            Toast.makeText(InternalActivity.this, "请授予全部权限，否则无法使用通话功能", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        openCall(phone);
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            Toast.makeText(InternalActivity.this, "被永久拒绝授权，请手动授予对应权限", Toast.LENGTH_SHORT).show();
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(InternalActivity.this, permissions);
                        } else {
                            System.out.println("授予权限失败");
                        }
                    }
                });
    }

    private void openCall(String callNumber) {
        CallUtil.getInstance().makeCall(callNumber);
        Intent i = new Intent(this, CallActivity.class);
        i.putExtra("callNumber", callNumber);
        startActivity(i);
    }

    private void requestData(String tenantId, String origId) {
        try {
            list.clear();
            JSONObject param = new JSONObject();

            JSONObject pageJson = new JSONObject();
            pageJson.put("pageNum", 1);
            pageJson.put("pageSize", 1000);

            JSONArray jsonArray = new JSONArray();
            JSONObject tenantIdJson = new JSONObject();
            tenantIdJson.put("key", "tenantId");
            tenantIdJson.put("value", tenantId);

            JSONObject orgIdJson = new JSONObject();
            orgIdJson.put("key", "orgId");
            orgIdJson.put("value", origId);

            jsonArray.put(tenantIdJson);
            jsonArray.put(orgIdJson);

            param.put("page", pageJson);
            param.put("parameters", jsonArray);

            Log.e(TAG, "getInternal: url is " + CallConstant.REQUEST_INTERNAL_CONTACT_URL);
            Log.e(TAG, "getInternal: param " + param);
            OkHttpUtils.httpPost(CallConstant.REQUEST_INTERNAL_CONTACT_URL, param.toString(), null,
                    new OkHttpUtils.ICallBack() {
                        @Override
                        public void onSuccessful(Call call, String data) {
                            Log.e(TAG, "getInternal contact onSuccessful: " + data);
                            runOnUiThread(() -> refreshUI(data));
                        }

                        @Override
                        public void onFailure(Call call, String errorMsg) {
                            Log.e(TAG, "getInternal contact onFailure: " + errorMsg);
                            runOnUiThread(() -> Toast.makeText(InternalActivity.this, errorMsg, Toast.LENGTH_SHORT).show());
                        }
                    });
        } catch (Exception e) {
            Log.e(TAG, "requestData: " + e.getMessage());
            runOnUiThread(() -> Toast.makeText(InternalActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }

    List<InternalContactModel> list = new ArrayList<>();

    private void refreshUI(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            if (jsonObject.getString("rtnCode").equals("0000")) {
                if (jsonObject.getJSONObject("data").optJSONArray("orgList") != null) {
                    JSONArray orgArray = new JSONArray(jsonObject.getJSONObject("data").getJSONArray("orgList").toString());
                    for (int i = 0; i < orgArray.length(); i++) {
                        JSONObject json = orgArray.getJSONObject(i);
                        list.add(new InternalContactModel(true, json.getString("id"), json.getString("title")));
                    }
                }
                if (jsonObject.getJSONObject("data").optJSONObject("userPage") != null) {
                    JSONArray userArray = new JSONArray(jsonObject.getJSONObject("data").getJSONObject("userPage").getJSONArray("dataResult").toString());
                    for (int i = 0; i < userArray.length(); i++) {
                        JSONObject json = userArray.getJSONObject(i);
                        list.add(new InternalContactModel(false, json.getString("name"), json.getString("mobile"), json.getString("telephoneNumber")));
                    }
                }
                internalAdapter.notifyDataSetChanged();
            } else {
                String msg = jsonObject.getString("rtnMsg");
                Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
